package com.salt.core.sms.aliyun;

//import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.salt.common.utils.IdGen;
import com.salt.common.utils.StringUtils;
import com.salt.core.redis.cache.SaltRedis;
import com.salt.core.sms.SmsTemplate;
import com.salt.core.sms.model.SmsCode;
import com.salt.core.sms.model.SmsData;
import com.salt.core.sms.model.SmsResponse;
import com.salt.core.sms.props.SmsProperties;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;

import java.time.Duration;
import java.util.Collection;
import java.util.Objects;

import static com.salt.core.sms.enums.SmsConstant.SMS_CACH_KEY;

/**
 * @Description
 * @Author salt
 * @Date 2022/9/7
 * @Version 1.0.1
 */
@AllArgsConstructor
public class AliSmsTemplate implements SmsTemplate {

    private static final long SMS_CACH_KEY_DEL = 10;  // 过期时间为10分钟
    private static final int SUCCESS = 200;
    private static final String SEND_SMS_SUCCESS_FLAG = "OK"; // 发送成功标志
    //private static final String DOMAIN = "dysmsapi.aliyuncs.com";  //短信服务的服务接入地址
    //private static final String VERSION = "2017-05-25";  //API的版本号
    //private static final String ACTION = "SendSms";  //API的名称

    private final IAcsClient acsClient;
    private final SaltRedis saltRedis;
    private final SmsProperties smsProperties;

    /*@Override
    public SmsResponse sendMessage(SmsData smsData, Collection<String> phones) {
        // 构建请求
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(DOMAIN);
        request.setSysVersion(VERSION);
        request.setSysAction(ACTION);
        //自定义参数，手机号，验证签名，短信模板，验证码（code）
        request.putQueryParameter("PhoneNumbers", StringUtils.join(phones)); // 接收短信的手机号码
        request.putQueryParameter("SignName", smsProperties.getSignName()); //短信签名名称
        request.putQueryParameter("TemplateCode", smsProperties.getTemplateId()); // 短信模板ID
        request.putQueryParameter("TemplateParam", JSONUtils.toJSONString(smsData.getParams())); // 短信模板变量对应的实际值
        try {
            CommonResponse response = acsClient.getCommonResponse(request);
            return new SmsResponse(response.getHttpStatus() == SUCCESS, response.getHttpStatus(), response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
            return new SmsResponse(Boolean.FALSE, HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        }
    }*/

    @Override
    public SmsResponse sendMessage(SmsData smsData, Collection<String> phones) {
        // 构建请求
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        request.setPhoneNumbers(StringUtils.join(phones, ",")); // 接收短信的手机号码
        request.setSignName(smsProperties.getSignName()); //短信签名名称
        request.setTemplateCode(smsProperties.getTemplateId()); // 短信模板ID
        //request.setTemplateParam(JSONUtils.toJSONString(smsData.getParams())); // 短信模板变量对应的实际值
        request.setTemplateParam(JSON.toJSONString(smsData.getParams())); // 短信模板变量对应的实际值
        try {
            SendSmsResponse response = acsClient.getAcsResponse(request);
            if (response.getCode() != null && Objects.equals(response.getCode(), SEND_SMS_SUCCESS_FLAG))
                return new SmsResponse(Boolean.TRUE, SUCCESS, response.getMessage());
        } catch (ClientException e) {
            e.printStackTrace();
            return new SmsResponse(Boolean.FALSE, HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        }
        return new SmsResponse();
    }

    @Override
    public SmsCode sendValidate(SmsData smsData, String phone) {
        SmsCode smsCode = new SmsCode();
        boolean temp = sendSingle(smsData, phone);
        if (temp && StringUtils.isNotBlank(smsData.getKey())) {
            String id = IdGen.uuid();
            String value = smsData.getParams().get(smsData.getKey());
            // 将ID、value存入缓存
            saltRedis.set(SMS_CACH_KEY + id + phone, value, Duration.ofMinutes(SMS_CACH_KEY_DEL));
            smsCode.setId(id).setValue(value);
        } else {
            smsCode.setSuccess(Boolean.FALSE);
        }
        String id = IdGen.uuid();
        String value = smsData.getParams().get(smsData.getKey());
        // 将ID、value存入缓存
        saltRedis.set(SMS_CACH_KEY + id + phone, value, Duration.ofMinutes(SMS_CACH_KEY_DEL));
        smsCode.setId(id).setValue(value);
        return smsCode;
    }

    @Override
    public boolean validateMessage(SmsCode smsCode) {
        String id = smsCode.getId();
        String value = smsCode.getValue();
        String cach = saltRedis.get(SMS_CACH_KEY + id);
        if (StringUtils.isNotBlank(cach) && StringUtils.equalsIgnoreCase(cach, value)) {
            saltRedis.del(SMS_CACH_KEY + id);
            return true;
        }
        return false;
    }


}
